import { Form, Popconfirm, Table, Space, Button, TableProps } from 'antd';

import { FC, useState } from 'react';

import EditableCell from './EditableCell';

import { EditOutlined, DeleteOutlined, SaveOutlined, CloseOutlined } from '@ant-design/icons';

export interface EditableRowTableProps extends Omit<TableProps<any>, 'onChange'> {}

const EditableRowTable: FC<EditableRowTableProps> = ({ columns, dataSource }) => {
  const [form] = Form.useForm();
  const [editingIndex, setEditingIndex] = useState(-1);

  const isEditing = (index: number) => index === editingIndex;

  const handleCloseConfirm = () => {
    setEditingIndex(-1);
  };

  const handleSaveClick = () => {
    form
      .validateFields()
      .then((formValues) => {})
      .finally();
  };

  const handleAddClick = () => {};

  const operationButtonsRender = (record: DynamicObjectAny, index: number) => {
    const handleEditClick = () => {
      setEditingIndex(index);
    };

    const handleDeleteClick = () => {};

    return (
      <Space>
        <Button type="link" icon={<EditOutlined />} onClick={handleEditClick} />
        <Button type="link" icon={<DeleteOutlined />} onClick={handleDeleteClick} />
      </Space>
    );
  };

  const editableOperationButtonsRender = (record: DynamicObjectAny, index: number) => {
    return (
      <Space>
        <Button type="link" icon={<SaveOutlined />} onClick={handleSaveClick} />
        <Popconfirm title="是否取消更改" onConfirm={handleCloseConfirm}>
          <Button type="link" icon={<CloseOutlined />} />
        </Popconfirm>
      </Space>
    );
  };

  const tableTitleRender = () => {
    return <Button onClick={handleAddClick}>新增</Button>;
  };

  const mergedColumns = [
    {
      title: '操作',
      dataIndex: 'operation',
      editable: false,
      fixed: true,
      width: 100,
      render: (_: any, record: DynamicObjectAny, index: number) => {
        const editable = isEditing(index);
        return editable
          ? editableOperationButtonsRender(record, index)
          : operationButtonsRender(record, index);
      },
    },
  ]
    .concat(columns)
    .filter((val) => val)
    .map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        ellipsis: true,
        onCell: (record: any, rowIndex?: number) => ({
          record,
          inputType: col.component,
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(rowIndex as number),
        }),
      };
    });

  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        title={tableTitleRender}
        bordered
        dataSource={dataSource}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={false}
      />
    </Form>
  );
};

EditableRowTable.defaultProps = {
  columns: [],
};

export default EditableRowTable;
